# Setup Frida Server on Android Emulator

$FRIDA_VERSION = "17.4.1"
$ARCH = "x86_64"
$FILENAME = "frida-server-$FRIDA_VERSION-android-$ARCH"
$URL = "https://github.com/frida/frida/releases/download/$FRIDA_VERSION/$FILENAME.xz"

Write-Host "`n[+] Setting up Frida Server..." -ForegroundColor Green
Write-Host "    Version: $FRIDA_VERSION" -ForegroundColor Yellow
Write-Host "    Architecture: $ARCH`n" -ForegroundColor Yellow

# 1. Download frida-server
if (!(Test-Path "$FILENAME.xz")) {
    Write-Host "[+] Downloading frida-server..." -ForegroundColor Cyan
    try {
        Invoke-WebRequest -Uri $URL -OutFile "$FILENAME.xz"
        Write-Host "[OK] Downloaded`n" -ForegroundColor Green
    } catch {
        Write-Host "[ERROR] Download failed: $_" -ForegroundColor Red
        Write-Host "`nPlease download manually from:" -ForegroundColor Yellow
        Write-Host $URL -ForegroundColor White
        exit 1
    }
} else {
    Write-Host "[OK] frida-server already downloaded`n" -ForegroundColor Green
}

# 2. Extract (need 7-Zip or similar)
if (!(Test-Path $FILENAME)) {
    Write-Host "[+] Extracting..." -ForegroundColor Cyan
    
    # Try using 7-Zip if available
    if (Test-Path "C:\Program Files\7-Zip\7z.exe") {
        & "C:\Program Files\7-Zip\7z.exe" e "$FILENAME.xz" -y | Out-Null
        Write-Host "[OK] Extracted`n" -ForegroundColor Green
    } else {
        Write-Host "[WARNING] 7-Zip not found" -ForegroundColor Yellow
        Write-Host "Please extract $FILENAME.xz manually" -ForegroundColor Yellow
        Write-Host "You can use: https://www.7-zip.org/`n" -ForegroundColor White
        exit 1
    }
}

# 3. Push to device
Write-Host "[+] Pushing frida-server to device..." -ForegroundColor Cyan
adb push $FILENAME /data/local/tmp/frida-server
if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] Push failed" -ForegroundColor Red
    exit 1
}
Write-Host "[OK] Pushed`n" -ForegroundColor Green

# 4. Set permissions
Write-Host "[+] Setting permissions..." -ForegroundColor Cyan
adb shell "su -c 'chmod 755 /data/local/tmp/frida-server'"
Write-Host "[OK] Permissions set`n" -ForegroundColor Green

# 5. Start frida-server
Write-Host "[+] Starting frida-server..." -ForegroundColor Cyan
adb shell "su -c '/data/local/tmp/frida-server &'"
Start-Sleep -Seconds 2

# 6. Verify
Write-Host "`n[+] Verifying..." -ForegroundColor Cyan
$processes = adb shell "ps | grep frida"
if ($processes) {
    Write-Host "[OK] frida-server is running!" -ForegroundColor Green
    Write-Host $processes -ForegroundColor Yellow
} else {
    Write-Host "[WARNING] frida-server might not be running" -ForegroundColor Yellow
    Write-Host "Check manually with: adb shell 'ps | grep frida'" -ForegroundColor White
}

Write-Host "`n[OK] Setup complete!`n" -ForegroundColor Green
Write-Host "You can now run: python test_hook.py" -ForegroundColor Cyan


